package com.example.java_gobang.game;

import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

//房间管理器类
//这个类也希望有唯一实例
@Component
public class RoomManager {
    private ConcurrentHashMap<String, Room> rooms = new ConcurrentHashMap<>();

    private ConcurrentHashMap<Integer, String> userIdToRoomId = new ConcurrentHashMap<>();


    public void add(Room room){
        rooms.put(room.getRoomId(), room);
        userIdToRoomId.put(room.getUser1().getUserId(), room.getRoomId());
        userIdToRoomId.put(room.getUser2().getUserId(), room.getRoomId());
    }

    public void add(Room room, Integer userid1, Integer userid2){
        rooms.put(room.getRoomId(), room);
        userIdToRoomId.put(userid1, room.getRoomId());
        userIdToRoomId.put(userid2, room.getRoomId()) ;
    }

    public void remove(String Roomid){
        Room room = rooms.get(Roomid);
        userIdToRoomId.remove(room.getUser1().getUserId());
        userIdToRoomId.remove(room.getUser2().getUserId());
        rooms.remove(Roomid);
    }

    public Room getRoomById(String roomId){
        return rooms.get(roomId);
    }

    public Room getRoomByUserId(int userId){
        String roomId = userIdToRoomId.get(userId);
        if(roomId == null)
            return null;
        return rooms.get(roomId);
    }
}
